##=============================================================================
## Appendix: Table 6
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

##--------
# Set seed
seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

##-------------
# Load Packages
ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse", "lme4", "sjPlot", "ordinal", "texreg", "hrbrthemes")


ipak(packages)

##---------
# Load Data
#setwd("~/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("clean_ukraine_data.RData")

# Random Effects at the District Level (ADM2)
fit <- glmer(compromise ~ 1 + wave + survival_mindset + per_idx_invcov + 
               fam_idx_invcov + frontline_b + ln_viina_two_months +
               displaced + sex + rus_ethnic + age + edu + job + finances + 
               (1 + wave + survival_mindset + per_idx_invcov + fam_idx_invcov | 
                  adm2_en), 
             data = dat, 
             family = binomial,
             control = glmerControl(optimizer = "bobyqa"))

# same singular fit problem; note alt. specification in main ms

sjPlot::tab_model(fit)
sjPlot::plot_model(fit)

labs <- c("(Intercept)",
          "Survey Wave",
          "Survival Mindset",
          "Personal Victimization",
          "Family Victimization",
          "Frontline Oblast",
          "Displaced",
          "Sex",
          "Ethnic Russian",
          "Age",
          "Education",
          "Employment",
          "Ln(VIINA) Two-Mos",
          "Socio-Economic Status")

texreg(list(fit), 
       dcolumn = TRUE,
       custom.coef.names = labs,
       custom.model.names = c("Compromise (Binary)"))

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================